package com.thread.threadfirst.rabbitMQPublisher.publisher;

import com.thread.threadfirst.rabbitMQPublisher.vo.RegisterVO;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class PublisherFirst {

    @Autowired
    //下面两个都可以 消息的发送组件
//    private AmqpTemplate rabbitTemplate;
    private RabbitTemplate rabbitTemplate;

    public String send1(String exchange, String routingKey, int batch) {
        for (int i = 0; i < batch; i++) {
            RegisterVO registerVO = new RegisterVO();
            registerVO.setUserId(9527L);
            registerVO.setPhone(UUID.randomUUID().toString());
            registerVO.setRegisterTime(new Date());
//            JSONObject vo=JSONObject.fromObject(registerVO);
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
//            CorrelationData 标识消息唯一性的主体对象，可以自己设定相关的参数，方便后续对某条消息做精确的定位
            CorrelationData cld=new CorrelationData(registerVO.getUserId().toString());
//            rabbitTemplate.convertAndSend(exchange, routingKey, registerVO);
//            rabbitTemplate.setConfirmCallback();  //消息投递到rabbitmq是否成功的回调函数，如果不成功，我们可以在该回调函数中做相关的处理
//            rabbitTemplate.setReturnCallback();  //消息被退回的回调函数
            rabbitTemplate.convertAndSend(exchange, routingKey, registerVO,cld);
            log.info("send msg: {},{}", i, registerVO);
        }
        return "success";
    }
}
